param(
  [Parameter(Mandatory=$true)]
  [string]$OrderCode
)

function Get-LatestJsonPath([string]$pattern) {
  $files = Get-ChildItem -Path "data" -Filter $pattern -File -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending
  if ($files -and $files.Count -gt 0) { return $files[0].FullName }
  return $null
}

function Load-JsonArray([string]$path) {
  if (-not $path) { return @() }
  try {
    $raw = Get-Content -Path $path -Raw -Encoding UTF8
    $obj = $raw | ConvertFrom-Json
    if ($obj -is [System.Collections.IEnumerable]) { return ,@($obj) }
    return ,@($obj)
  } catch { return @() }
}

function Get-Prop($o, $name) {
  if ($null -eq $o) { return $null }
  if ($o.PSObject.Properties.Match($name).Count -gt 0) { return $o.$name }
  return $null
}

function To-Scalar($v) {
  if ($null -eq $v) { return $null }
  if ($v -is [string] -or $v -is [int] -or $v -is [double] -or $v -is [decimal] -or $v -is [bool]) { return $v }
  # Complex -> JSON string for stable compare
  return ($v | ConvertTo-Json -Depth 20 -Compress)
}

function Compare-Duplicates([array]$items, [string]$label) {
  $dups = @($items | Where-Object { (Get-Prop $_ 'code') -eq $OrderCode })
  Write-Host ("[$label] Found entries: {0}" -f $dups.Count)

  if ($dups.Count -le 1) {
    if ($dups.Count -eq 1) {
      Write-Host "  Only one entry found. No duplicates to compare."
    } else {
      Write-Host "  No entry found for the given code."
    }
    return
  }

  # Print key summary of each entry
  for ($i = 0; $i -lt $dups.Count; $i++) {
    $o = $dups[$i]
    $summary = [ordered]@{
      idx = $i
      id = (Get-Prop $o 'id')
      code = (Get-Prop $o 'code')
      status = (Get-Prop $o 'status')
      vouchdate = (Get-Prop $o 'vouchdate')
      createTime = (Get-Prop $o 'createTime')
      pubts = (Get-Prop $o 'pubts')
      orgId = (Get-Prop $o 'orgId')
      orgName = (Get-Prop $o 'orgName')
      departmentName = (Get-Prop $o 'departmentName')
      OrderProduct_quantity = (Get-Prop $o 'OrderProduct_quantity')
      OrderProduct_completedQuantity = (Get-Prop $o 'OrderProduct_completedQuantity')
      OrderProduct_incomingQuantity = (Get-Prop $o 'OrderProduct_incomingQuantity')
    }
    Write-Host ("  Entry #{0}: {1}" -f $i, ( $summary | ConvertTo-Json -Compress ))
  }

  # Properties comparison
  $propSets = $dups | ForEach-Object { ,(@($_.PSObject.Properties.Name | Sort-Object)) }
  $base = $propSets[0]
  for ($i = 1; $i -lt $propSets.Count; $i++) {
    $cmp = Compare-Object -ReferenceObject $base -DifferenceObject $propSets[$i]
    if ($cmp) {
      Write-Host ("  Property set differs between entry #0 and entry #{0}:" -f $i)
      $cmp | ForEach-Object { Write-Host ("    {0} {1}" -f $_.SideIndicator, $_.InputObject) }
    }
  }

  # Value differences on common properties
  $common = $base
  for ($i = 1; $i -lt $propSets.Count; $i++) {
    $common = @( $common | Where-Object { $propSets[$i] -contains $_ } )
  }
  $diffs = @()
  foreach ($p in $common) {
    $vals = @()
    foreach ($o in $dups) { $vals += ,(To-Scalar (Get-Prop $o $p)) }
    $uniq = $vals | Select-Object -Unique
    if ($uniq.Count -gt 1) {
      $diffs += [pscustomobject]@{ prop = $p; values = $uniq }
    }
  }

  if ($diffs.Count -gt 0) {
    Write-Host ("  Value differences across duplicates (showing up to 40):")
    $diffs | Sort-Object prop | Select-Object -First 40 | ForEach-Object {
      $vs = ($_.values | ForEach-Object { if ($_ -is [string]) { '"' + $_ + '"' } else { $_ } }) -join ' | '
      Write-Host ("    - {0}: {1}" -f $_.prop, $vs)
    }
    if ($diffs.Count -gt 40) { Write-Host ("    ... and {0} more" -f ($diffs.Count - 40)) }
  } else {
    Write-Host "  All common properties have identical values (within first two entries)."
  }
}

$ordersPath = Get-LatestJsonPath 'erp_orders_*.json'
$detailsPath = Get-LatestJsonPath 'erp_order_details_*.json'

Write-Host "Using orders:  $ordersPath"
Write-Host "Using details: $detailsPath"

$orders = Load-JsonArray $ordersPath
$details = Load-JsonArray $detailsPath

Compare-Duplicates -items $orders -label 'Orders'
Compare-Duplicates -items $details -label 'Details'
